<!--
 * @Author: licongwei
 * @Date: 2022-03-15 15:17:47
 * @FileDescription:Cpi
-->
<template>
  <com-box :title="data.title">
    <template #titleRight>
      <div class="con-btn">
        <el-tooltip
          class="box-item"
          effect="dark"
          content="请点击数据点进行操作！"
          placement="top-start"
        >
          <button @click="handMsg('add')">
            <el-icon><circle-check /></el-icon>
            新增
          </button>
        </el-tooltip>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="请点击数据点进行操作！"
          placement="top-start"
        >
          <button @click="handMsg('del')">
            <el-icon><circle-close /></el-icon>
            删除
          </button>
        </el-tooltip>
      </div>
    </template>
    <div class="box">
      <!-- <div class="box-top" v-show="data.title != ''">
        <p>价格日指数</p>
      </div> -->
      <div class="box-radio">
        <el-radio-group
          v-show="data.title != ''"
          v-model="data.radio"
          class="ml-4"
          @change="changeRadio"
        >
          <el-radio label="环比" size="large">环比</el-radio>
          <el-radio label="同比" size="large">同比</el-radio>
        </el-radio-group>
      </div>
      <!-- <charts v-if="data.params.show" class="line-chart" :params="data.params">
      </charts> -->
      <loading v-show="data.params.loading" />
      <div ref="chart" style="width: 100%; height: 100%"></div>
    </div>
  </com-box>
</template>
<script lang="ts" setup>
import { reactive, defineExpose, defineEmits, ref } from 'vue'
import httpRequest from '@/service'
import request from '@/utils/request'
import loading from '@/charts/loading.vue'
import comBox from '@/components/comBox/comBox.vue'
import { ElRadio, ElRadioGroup, ElMessage, ElTooltip } from 'element-plus'
import { getZSDate } from '@/utils/auth'
import * as echarts from 'echarts'
// import myIcon from '../img/tooltip.png'
const emit = defineEmits(['tableClick'])
import {
  CircleCheck,
  // RefreshRight,
  CircleClose
  // Warning,
  // Close
} from '@element-plus/icons-vue'
const refreshData = (list: any, radio: any) => {
  data.list = list
  data.queryType = radio
  data.getData(list, radio)
}
defineExpose({
  refreshData
})
const changeRadio = () => {
  data.getData(data.list, data.queryType)
}
const handMsg = (val: any) => {
  const { dataList, selectPoint } = data.params
  const dataPoint = dataList[selectPoint.dataIndex] // 点击的数据点对应的数据
  if (!selectPoint.name) {
    ElMessage({
      message: '请先选择要设置的数据点！',
      showClose: true,
      offset: 130,
      duration: 2000,
      type: 'warning'
    })
    return
  }
  if (val == 'add') {
    if (dataPoint['msg' + (selectPoint.componentIndex + 1)].reason_id) {
      ElMessage({
        message: '此数据点已设置影响因素！',
        showClose: true,
        offset: 130,
        duration: 2000,
        type: 'warning'
      })
      return
    }
    emit('tableClick', val, data.params.selectPoint, data.list)
  } else {
    let id = ''
    if (dataPoint['msg' + (selectPoint.componentIndex + 1)].reason_id) {
      id = dataPoint['msg' + (selectPoint.componentIndex + 1)].reason_id
    }
    if (id == '') {
      ElMessage({
        message: '此数据点未设置影响因素，无法删除！',
        showClose: true,
        offset: 130,
        duration: 2000,
        type: 'warning'
      })
      return
    }
    request(
      `/dataservice/priceIndex/deleteWaveReason?id=${id}`,
      {},
      'get',
      ''
    ).then((res: any) => {
      if (res.code == 200) {
        ElMessage({
          message: '操作成功！',
          showClose: true,
          offset: 130,
          duration: 2000,
          type: 'success'
        })
        data.getData(data.list, data.queryType)
      }
    })
  }
}
const chart = ref(null)
let myChart: any
// const currentHighlight = ref({ seriesIndex: null, dataIndex: null }) // 记录当前高亮点
// 点击事件处理函数
const handleChartClick = (params: any) => {
  if (params.componentType === 'series') {
    data.params.options = JSON.parse(JSON.stringify(data.params.orginOptions))
    data.params.options.series[params.seriesIndex].markPoint.data.push({
      coord: [params.name, params.data],
      value: '已选择',
      symbol: 'roundRect',
      itemStyle: {
        color: '#14519c'
      },
      label: {
        color: '#fff'
      },
      symbolSize: [50, 30]
    })
    myChart.setOption(data.params.options)
    data.params.selectPoint = params
  } else if (params.componentType === 'markPoint') {
    emit('tableClick', 'query', params, data.params.msgList)
  }
}
const handleZoome = (params: any) => {
  data.params.orginOptions.dataZoom[0].start = params.start
  data.params.orginOptions.dataZoom[0].end = params.end
}
const data: any = reactive({
  radio: '环比',
  list: [],
  queryType: '',
  value: '',
  title: '',
  isGroup: false,
  params: {
    chartInstance: null,
    msgList: [],
    selectPoint: {},
    dataList: [],
    loading: true,
    show: true,
    color: [
      '#FFF100',
      '#5dec9d',
      '#ea68a2',
      '#1da7ff',
      '#ec6941',
      '#0df1ff',
      '#86bcff',
      '#93FF00'
    ],
    map: {
      value: '价格'
    },
    orginOptions: {},
    options: {
      legend: {
        right: 0,
        top: 15,
        width: '70%',
        textStyle: {
          color: '#fff',
          fontSize: 13
        }
      },
      tooltip: {
        show: true,
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
          snap: true
        },
        // triggerOn: 'click',
        // alwaysShowContent: true,
        confine: true,
        backgroundColor: '#1959a7',
        borderColor: '#4beeff',
        borderWidth: 1,
        padding: 12,
        textStyle: {
          color: '#fff',
          fontSize: 14
        }
      },
      grid: {
        top: 80,
        bottom: 34,
        left: 25,
        righr: '0%',
        width: '95%',
        containLabel: true
      },
      xAxis: {
        lineStyle: {
          color: 'rgba(126,206,244,0.3)'
        },
        axisTick: {
          show: false
        },
        // axisPointer: {
        //   handle: {
        //     show: true,
        //     icon: 'none'
        //   }
        // },
        axisLabel: {
          fontSize: 14,
          color: '#fff',
          formatter: function (value: string) {
            const srt = value.split('-')
            return srt[0] + '-' + srt[1] + (srt[2] ? '-' + srt[2] : '')
          }
        }
      },
      yAxis: {
        name: '',
        splitLine: {
          show: false
        },
        nameTextStyle: {
          align: 'left',
          color: '#46ede8',
          fontSize: 14,
          fontWeight: 'bold'
        },
        min: 60,
        axisLabel: {
          fontSize: 14,
          color: '#fff'
        }
      },
      dataZoom: [
        {
          show: true,
          type: 'slider',
          start: 0,
          end: 100,
          width: '80%',
          height: 15,
          left: '10%',
          bottom: '13',
          borderColor: '#166beb',
          handleStyle: {
            color: '#166beb',
            borderColor: '#166beb',
            borderWidth: 4
          },
          moveHandleSize: 10,
          moveHandleStyle: {
            color: '#166beb'
          },
          textStyle: {
            color: '#00c6ff'
          },
          emphasis: {
            handleStyle: {
              color: '#00c6ff',
              borderColor: '#00c6ff',
              borderWidth: 4
            },
            moveHandleStyle: {
              color: '#00c6ff'
            }
          }
        }
      ],
      series: []
    }
    // event: {
    //   click: (params: any) => {
    //     console.log(params)
    //   }
    // }
  },
  getData: (val: any, val2: any) => {
    data.params.loading = true
    const date: any = getZSDate()
    const dom = chart.value
    if (dom) {
      if (myChart !== null && myChart !== '' && myChart !== undefined) {
        myChart.dispose()
      }
      myChart = echarts.init(dom)
    }
    httpRequest
      .get({
        url: 'M5ZSLine',
        params: {
          dataType: data.radio,
          queryType: val2,
          priceIndexId: val.length > 0 ? val.join() : '',
          startDate: JSON.parse(date)[0],
          endDate: JSON.parse(date)[1]
        }
      })
      .then((res) => {
        if (res.code === 200) {
          if (res.code === 200 && Object.keys(res.map).length > 0) {
            data.params.msgList = []
            data.params.dataList = []
            data.params.selectPoint = {}
            data.params.dataList = res.data
            data.params.show = true
            data.title = ''
            const xAxisData = res.data.map((item: any) => item.name)
            data.params.options.xAxis.data = xAxisData
            let series: any = []
            Object.keys(res.map).forEach((i: any, j: number) => {
              let markPoint: any = []
              const seriesData = res.data.map((item: any) => {
                // 处理空值
                const value = item[i]
                return value === '' || value === null ? null : Number(value)
              })
              res.data.forEach((item: any) => {
                let msg = 'msg' + (j + 1)
                if (item[msg].reason_id) {
                  data.params.msgList.push(item[msg])
                  const titleLength = item[msg].title.length
                  markPoint.push({
                    coord: [item.name, item[i]],
                    name: item[msg].reason_id,
                    value: `${item[msg].title}`,
                    // symbol: 'roundRect',
                    symbol:
                      'path://m 20.013628 0 l 84.37401 0 l 0 0 c 11.053215 -1.04756605e-14 20.013626 9.282301 20.013626 20.7326 c 0 11.450296 -8.960411 20.7326 -20.013626 20.7326 l -84.37401 0 l 0 0 c -11.053222 0 -20.013628 -9.282303 -20.013628 -20.7326 c -5.2380687e-15 -11.450298 8.960406 -20.7326 20.013628 -20.7326 z',
                    symbolSize: [
                      titleLength > 4 ? titleLength * 17 : titleLength * 21,
                      30
                    ],
                    symbolOffset: [0, '-85%'],
                    itemStyle: {
                      color: data.params.color[j],
                      borderWidth: 0,
                      opacity: 0.85
                    },
                    label: {
                      color: '#000',
                      fontSize: 14,
                      position: 'inside'
                    }
                  })
                  // 三角形箭头
                  markPoint.push({
                    coord: [item.name, item[i]],
                    name: item[msg].reason_id,
                    value: `${item[msg].title}`,
                    symbol: 'triangle',
                    symbolSize: [16, 12],
                    symbolRotate: 180,
                    symbolOffset: [0, '-70%'],
                    itemStyle: {
                      color: data.params.color[j]
                    },
                    label: {
                      show: false
                    }
                  })
                }
              })
              series.push({
                name: res.map[i],
                data: seriesData,
                type: 'line',
                lineStyle: {
                  color: data.params.color[j]
                },
                itemStyle: {
                  color: data.params.color[j]
                },
                areaStyle: {
                  opacity: 0
                },
                label: {
                  show: false
                },
                symbolSize: 7, //折线点的大小
                smooth: true,
                connectNulls: true,
                markPoint: {
                  symbol: 'roundRect',
                  data: markPoint,
                  label: {
                    color: '#fff',
                    fontSize: 14,
                    lineHeight: 20
                  },
                  animation: false,
                  symbolRotate: 0,
                  itemStyle: {
                    borderWidth: 0
                  }
                }
              })
            })
            data.params.options.series = series
            if (!data.params.selectPoint.grid) {
              if (res.data.length >= 10) {
                data.params.options.dataZoom[0].start = 50
              } else {
                data.params.options.dataZoom[0].start = 0
              }
            }
            data.title = res.title
            let options = data.params.options
            data.params.orginOptions = options
            myChart.setOption(options)
            myChart.on('click', handleChartClick)
            myChart.on('dataZoom', handleZoome)
          } else {
            data.params.show = false
          }
          setTimeout(() => {
            data.params.loading = false
          }, 500)
        }
      })
      .catch(() => {
        console.log('请求失败')
      })
  }
})

// data.getData()
</script>
<style lang="less" scoped>
.con-btn {
  display: flex;
  justify-content: flex-end;
  margin-top: 21px;
  button {
    cursor: pointer;
    background: #14519c;
    padding: 2px 10px;
    color: #fff;
    font-weight: bold;
    box-shadow: 0 0 7px #297eea inset;
    border: 1px solid transparent;
    margin: 0px 10px;
    display: flex;
    align-items: center;
    font-size: 18px;
    i {
      font-size: 19px;
      margin-right: 5px;
    }
  }
}
.box {
  width: 100%;
  height: 100%;
  padding: 20px;
  padding-top: 0px;
  position: relative;
  &-top {
    border: 1px solid rgb(94, 220, 255);
    position: absolute;
    background-color: rgb(26, 64, 181);
    width: 140px;
    height: 42px;
    font-size: 18px;
    font-family: 'Microsoft YaHei';
    color: rgb(255, 255, 255);
    font-weight: bold;
    top: 20px;
    left: 90px;
    box-shadow: inset 0px 0px 15.52px 0.48px rgba(39, 115, 230, 0.5);
    border-radius: 18px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
  }

  &-radio {
    z-index: 10;
    position: absolute;
  }
  &::v-deep(.el-radio) {
    --el-radio-input-bg-color: transparent;
    --el-radio-input-border: 2px solid #194998;
    .el-radio__input.is-checked .el-radio__inner {
      background-color: transparent;
    }
    .el-radio__input.is-checked .el-radio__inner::after {
      // transform: translate(-50%, -50%) scale(1.4);
      background-color: #00ffff;
    }
    .el-radio__inner::after {
      width: 5px;
      height: 5px;
    }
  }
  &::v-deep(.el-radio__label) {
    color: rgb(80, 162, 239);
    font-size: 15px;
  }
}
</style>
